<?php

/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/9/13
 * Time: 13:55
 */
class Block
{
    public $prevHash;//前一个区块的hash
    public $hash;//当前区块的hash
    public $timeStamp;//当前区块生成时间戳
    public $data;//区块保存的数据
    public $nonce;//成员变量，用于记录计数器

    public function __construct($prevHash, $data)
    {
        $this->prevHash = $prevHash;
        $this->timeStamp = time();
        $this->data = $data;
//        $this->setBlockHash();
        $this->findBlockHash();
    }

    /**
     * 得到hash值
     */
    public function setBlockHash()
    {
        $data = serialize($this);
        $this->hash = hash('sha256', $data);
    }

    /**
     * 获取hash值
     * @return string
     */
    public function getBlockHash()
    {
        return $this->hash;
    }

    private function prepareData($nonce)
    {
        return json_encode([
            $this->prevHash,
            $this->timeStamp,
            $this->data,
            $nonce,
        ]);
    }

    /**
     * 寻找满足条件的区块
     * @return bool
     */
    public function findBlockHash()
    {
        $found = false;
        $condition = '000000000';//Hash值前N个字符必须等于$condition
        $condlength = strlen($condition);
//        printf("Mining the block containing \"%s<br>", $this->data);
        for ($nonce = 0; $nonce < PHP_INT_MAX; $nonce++){
            $data=$this->prepareData($nonce);
            $hash=hash('sha256',$data);
//            printf("\r%d: %s", $nonce, $hash);
            if (substr($hash, 000000000, $condlength) === $condition) {
                $found = true;
                break;
            }
        }
        if ($found) {
            $this->nonce = $nonce;
            $this->hash = $hash;
        }
        return $found;
    }

    /**
     * 验证区块是否合法
     * @return string
     */
    public function validate()
    {
        $condition='0';
        $condlength = strlen($condition);
        $data = $this->prepareData($this->nonce);
        return substr(hash('sha256', $data), 0, $condlength)=== $condition;;
    }
}
